import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from 'taro-ui'
import {Image, Navigator, Text, View} from '@tarojs/components'
import {connect} from 'react-redux'
import {Access, CityLocation as CityLocationType} from '../../utils/server.interface'
import {user} from '../../utils/user.service'
import {http} from "../../utils/http";
import {SELF_GET_LIST, RESOURCE_URL} from "../../constants/api";
import Headercar from "../components/header-car/header-car";
import {getHeadTop, vcmonitor} from "../../utils/tools";
import {location} from "../../utils/location.service";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './list.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: Access[] | false
  selfAdd: Access | false
  fromOrder: boolean
  selfId: number
  limit: number
  ids: string
  lng: number
  lat: number
  searchBarTop: number
  search: string
  klat: number
  klng: number
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    selfId: 0,
    list: [],
    selfAdd: false,
    fromOrder: false,
    limit: 99,
    ids: '',
    lng: 0,
    lat: 0,
    searchBarTop: 0,
    search: '',
    klat: 0,
    klng: 0,
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {

      await h5Wx.getConfig()
    }
    this.shareParams = await user.getSellerParams()
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    const {ids = 0, lat = 0, lng = 0, selfId} = Taro.getCurrentInstance().router.params;
    const adds = await this.getAdds(this.page, this.state.limit, lat, lng, ids, selfId)
    let selfAdd = this.state.selfAdd
    const list = []
    if (adds && adds.length > 0) {
      adds.map(item => {
        if (item.id == selfId) {
          selfAdd = item
        } else {
          list.push(item)
        }
      })
    }
    this.setState({list, selfAdd, selfId, ids, lat, lng, searchBarTop})
  }

  async componentDidShow() {
    vcmonitor(this);
    this.shareParams = await user.getSellerParams()
    const location = Taro.getStorageSync('location')
    // const pages = Taro.getCurrentPages()
    // const currPage = pages[pages.length - 1]; //当前页面
    if (location) {
      //console.log(location)
      this.setState({search: location.poiname, klat: location.latlng.lat, klng: location.latlng.lng}, () => {
        Taro.removeStorageSync('location')
        this.searchVal()
      })
    }
  }

  searchChange(val) {
    this.setState({search: val})
  }

  checklocation() {
    const that = this
    if (process.env.TARO_ENV === 'h5') {
      Taro.navigateTo({url: '/other/address/h5map'});
    } else {
      Taro.chooseLocation({
        success: function (res) {
          //console.log(res)
          if (res.errMsg.indexOf('ok') > -1) {
            that.setState({search: res.name, klat: res.latitude, klng: res.longitude}, () => {
              that.searchVal()
            })
          }
        },
        fail: function (err) {
          //console.log(err)
          that.setState({search: '', klat: 0, klng: 0})
        }
      })
    }

  }

  referSearch(e) {
    const that = this
    e.stopPropagation()
    that.setState({search: '', klat: 0, klng: 0}, () => {
      that.searchVal()
    })
  }

  async searchVal() {
    Taro.showLoading({
      title: '搜索中',
    })
    const {search, selfId, ids, lat, lng, klat, klng} = this.state
    const adds = await this.getAdds(this.page, this.state.limit, lat, lng, ids, selfId, search, klat, klng)
    let selfAdd = false
    const list = []
    if (adds && adds.length > 0) {
      adds.map(item => {
        if (item.id == selfId) {
          selfAdd = item
        } else {
          list.push(item)
        }
      })
    }

    this.setState({list, selfAdd}, () => {
      Taro.hideLoading()
    })
  }

  checkSelf(index) {
    let {selfAdd, list} = this.state
    if (index != undefined) {
      selfAdd = list[index]
    }
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - 2]
    if (prevPage) {
      prevPage.data.access = selfAdd
      Taro.navigateBack({
        delta: 1
      })
    } else {
      Taro.showToast({title: '错误操作'})
    }
  }

  async getAdds(page = 1, limit = 99, lat = 0, lng = 0, ids = '', selfId = 0, keywords = '', klat? = 0, klng? = 0) {
    let data = {page, limit, lat, lng, ids, keywords, selfId}
    if (klat && klng && keywords) {
      data = {page, limit, lat, lng, ids, keywords, selfId, klat, klng}
    }
    const addData = await http.carGet<Access[]>(SELF_GET_LIST, data)
    if (addData) {
      if (addData.length < limit) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return addData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getAdds(this.page, this.state.limit, this.state.lat, this.state.lng, this.state.ids, this.state.selfId)
      this.setState({list: [...old, ...newData]})
    }
  }

  async onPullDownRefresh() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', list: []}, async () => {
      const adds = await this.getAdds(this.page, this.state.limit, this.state.lat, this.state.lng, this.state.ids, this.state.selfId)
      let selfAdd = false
      const list = []
      if (adds && adds.length > 0) {
        adds.map(item => {
          if (item.id == selfId) {
            selfAdd = item
          } else {
            list.push(item)
          }
        })
      }
      this.setState({list, selfAdd}, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  render() {
    const {loadMoreStatus, search, list, searchBarTop, selfAdd, klat, klng} = this.state

    return (
      <View className='address-list-root'>
        <GzhAuth />
        {process.env.TARO_ENV != 'h5' && process.env.TARO_ENV != 'tt' &&
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headercar color='white' title='自提点选择' tabColor='#fff' backgroundColor='none' bcolor='#fff' />
        </View>}
        <View className='search-box'>
          <View className='search-val'
            onClick={this.checklocation.bind(this)}
          >{search ? search : "请输入您的小区地址"} {search &&
          <View onClick={this.referSearch.bind(this)} className='close-search'><AtIcon value='close' size='13'
            color='#fff'
          /></View>}</View>
          <View className='search-btn' onClick={this.searchVal.bind(this)}>
            <AtIcon prefixClass='xxhz' value='sousuo' size='20' color='#838383' />
          </View>
        </View>
        {selfAdd &&
        <View className='hear-box' onClick={this.checkSelf.bind(this)}>
          <View className='title'>
            <AtIcon prefixClass='xxhz' value='dingwei' size='22' color='#fe9f00' />{selfAdd.name}</View>
          <View className='address'>{selfAdd.address}</View>
          <View className='show'><Text>当前自提点</Text><AtIcon value='chevron-right' size='14'
            color='#fe9f00'
          /></View>
        </View>}
        {(list && list.length > 0) && <View className='list'>
          <View className='title'><Text>附近自提点</Text></View>
          {list.map((item, index) =>
            <View className='item-box' key={index} onClick={this.checkSelf.bind(this, index)}>
              <View className='name'>{item.name}</View>
              <View className='address'>{item.address}</View>
              <View className='distance'>{item.phone &&
              <View className='left'><AtIcon prefixClass='xxhz' value='phone' size='12'
                color='#c0c0c0'
              />{item.phone}</View>}<View
                className='right'
              ><AtIcon prefixClass='xxhz' value='dingwei' size='12'
                color='#c0c0c0'
              />{item.distance}</View></View>
            </View>
          )}
        </View>}
        {loadMoreStatus != 'loading' && list && list.length == 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/addressnull.png`} mode='widthFix' />
          {(klat && klng) ?
            <View className='text'>您搜索的‘{search}’
              <Navigator className='nav-li' url='/distributor/contact/contact' hoverClass='none'>附近暂无自提点，去<Text
                className='red'
              >联系客服</Text></Navigator>
            </View>
            :
            <View className='text'>卖家真懒~
              <Navigator className='nav-li' url='/distributor/contact/contact' hoverClass='none'>还没设置自提点，去<Text
                className='red'
              >联系客服</Text></Navigator>
            </View>
          }
        </View>}
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
